package lerry.load.loader;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
import flash.utils.Function;

class ImgLoader extends EventDispatcher {
	var loader:Loader;
	var cb:Function;
	var data:Dynamic;
	
	public function new() {
		super();
		loader = new Loader();
	}
	public function load(url:String, ?callBack:Function):Void {
		var na = url.substr(url.length - 3, url.length);
		if (na != "jpg"&&na != "png"&&na!="gif") {
			throw "incorrect image type";
		}
		cb=callBack;
		loader.load(new URLRequest(url));
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadCom);
		loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onError);
	}
	function onError(e:IOErrorEvent):Void {
		dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
	}
	
	function onLoadCom(event:Event):Void {
		loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadCom);
		data = event.target.content;
		if (cb != null) cb();
		dispatchEvent(new Event(Event.COMPLETE));
	}
	
	public function getBitmap():Bitmap {
		return cast(data,Bitmap);
	}
	public function getBitmapData():BitmapData {
		var b = cast(data, Bitmap);
		return b.bitmapData;
	}
	
	public function dispose():Void {
		loader.unloadAndStop();
		loader = null;
		cb = null;
		data = null;
	}
}

